package com.product.android.utils;

import android.app.Activity;
import android.content.Context;
import android.text.ClipboardManager;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;

import com.common.android.utils.smiley.Smiley;
import com.common.android.utils.smiley.SmileyValueArray;
import com.common.android.utils.smiley.Smileyhelper;

/**
 * @ClassName MyPasteListener
 * @Function 监听粘贴操作
 * @Reason
 *
 * @author HuangYK
 * @version v1.3.2
 * @Date 2013 2013-12-12 下午4:31:59
 *
 * @see
 */
public class MyPasteListener implements InputFilter {
    public interface onPasteCatSmileyListener{
        void onPasteCatSmiley(int id);
    }
    private boolean mIsDoPaste = false;
    private int mSelection;
    private ClipboardManager mClipboardManager;
    private onPasteCatSmileyListener mPasteCatSmileyListener;
    private boolean mHasDone = false;
    /**
     * 最大长度
     */
    private int mMaxLength = 0;
    /**
     * 表情的类型（Smiley.TYPE_WEIBO|Smiley.TYPE_CHAT)
     */
    private int mType;

    public MyPasteListener(Context context) {
        mClipboardManager = (ClipboardManager) context
                .getSystemService(Activity.CLIPBOARD_SERVICE);
    }

    public void setOnPasteCatSmileyListener(onPasteCatSmileyListener listener){
        mPasteCatSmileyListener=listener;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
            int dend) {
        CharSequence sourceTemp = source;
        source = cutSmileyCharSequenceInFilter(dest.length(), source);

        if (mClipboardManager.getText() != null && !mIsDoPaste) {
            if (mHasDone) {
                mHasDone = false;
                return filterCat(source);
            }
            String strClipboard = mClipboardManager.getText().toString();
            if (sourceTemp.toString().equals(strClipboard)) {
                mIsDoPaste = true;
                if (mType == Smiley.TYPE_WEIBO) {
                    source = Smileyhelper.getInstance().showSmileyByTip(source.toString(),
                            Smiley.TYPE_CHAT);
                } else {
                    source = Smileyhelper.getInstance().convertMXSmileyToIMSmiley(
                            source.toString(), Smiley.TYPE_WEIBO);
                }
                mSelection = dstart + source.length();
                return filterCat(source);
            } else {
                mSelection = dstart + source.length();
            }
        } else {
            mSelection = dstart + source.length();
            return filterCat(source);
        }
        return null;
    }

    /**过滤猫表情的粘贴操作
     * 解决BUG #40462 【外网--聊天页面】长按猫表情进行复制，在消息输入框进行复制后是空的。
     * @param source
     * @return
     */
    private CharSequence filterCat(CharSequence source){
        if (mPasteCatSmileyListener==null){
            return source;
        }
        String text=source.toString();
        if (text.startsWith(Smiley.IMGSTART) && text.endsWith(Smiley.IMGEND)){
            text=text.replace(Smiley.IMGSTART, "");
            text=text.replace(Smiley.IMGEND, "");
            try {
                int id=Integer.valueOf(text);
                int start=SmileyValueArray.CAT_ID[0];
                int end=SmileyValueArray.CAT_ID[SmileyValueArray.CAT_ID.length-1];
                if (id>=start && id<=end){
                    mPasteCatSmileyListener.onPasteCatSmiley(id);
                    return "";
                }
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
        return source;
    }

    public void setIsDoPaste(boolean flag) {
        mIsDoPaste = flag;
    }

    public void setSelection(int index) {
        mSelection = index;
    }

    public boolean getIsDoPaste() {
        return mIsDoPaste;
    }

    public int getSelection() {
        return mSelection;
    }

    public void setHasDone(boolean flag) {
        mHasDone = flag;
    }

    public boolean getHasDone() {
        return mHasDone;
    }

    /**
     * 设置最大长度值
     *
     * <br>Created 2014-8-18 下午6:22:01
     * @param maxLength 最大长度值
     * @author       wangds
     */
    public void setMaxLength(int maxLength) {
        this.mMaxLength = maxLength;
    }

    /**
     * 设置类别
     *
     * <br>Created 2014-8-18 下午6:22:16
     * @param type 表情的类型（Smiley.TYPE_WEIBO|Smiley.TYPE_CHAT)
     * @author       wangds
     */
    public void setType(int type) {
        this.mType = type;
    }

    /**
     * 过滤粘贴截取的表情，防止表情
     *
     * <br>Created 2014年11月11日 下午5:48:55
     * @param source 新增字符（粘贴字符）
     * @param destLength 原输入字符的长度
     * @return
     * @author       wangds
     */
    private CharSequence cutSmileyCharSequenceInFilter(int destLength, CharSequence source) {
        if(mMaxLength == 0 || mMaxLength >= destLength + source.length()){
            return source;
        }
        if (mClipboardManager.getText() != null) {
            String strClipboard = mClipboardManager.getText().toString();

            if (source.toString().equals(strClipboard.toString())) {// 新增内容与剪切板一致则为粘贴事件
                StringBuffer contentBuffer ;
                // 超过限制长度时的截取功能 -by wangds 2014.08.18
                int cutSelection;// 截取位置
                contentBuffer = new StringBuffer(source);
                int length;
                while (mMaxLength < destLength + contentBuffer.length()) {// 长度超过限制时截取
                    cutSelection = Smileyhelper.getInstance().delSmileyFromString(
                            contentBuffer.toString(), contentBuffer.length(), Smiley.TYPE_WEIBO);
                    if(cutSelection == -1){
                        cutSelection = Smileyhelper.getInstance().delSmileyFromString(
                                contentBuffer.toString(), contentBuffer.length(), Smiley.TYPE_CHAT);
                    }
                    length = contentBuffer.length();
                    if (length == 0) {
                        break;
                    } else if (cutSelection == -1) {// 最后删除的不是表情的情况直接删除最后一个字符
                        cutSelection = length - 1;
                    }
                    contentBuffer.delete(cutSelection, contentBuffer.length());
                }
                source = contentBuffer.toString();
            }
        }

        return source;
    }

}
